<template>
  <div :class="className" :style="{ height: '100%', width: '100%' }" />
</template>

<script setup lang="ts">
import { onMounted, onBeforeUnmount, ref, watch } from 'vue'
import * as echarts from 'echarts'
import { debounce } from 'lodash-es'

const props = withDefaults(defineProps<{
  className?: string
}>(), {
  className: 'radar-chart'
})

const chart = ref<echarts.ECharts | null>(null)

// 防抖处理 resize
const handleResize = debounce(() => {
  if (chart.value) {
    chart.value.resize()
  }
}, 100)

const initChart = async () => {
  const chartDom = document.getElementsByClassName(props.className)[0]
  if (!chartDom) return

  chart.value = echarts.init(chartDom as HTMLElement)

  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['预算分配', '实际开销']
    },
    radar: {
      // shape: 'circle',
      indicator: [
        { name: '销售', max: 10000 },
        { name: '管理', max: 10000 },
        { name: '信息技术', max: 10000 },
        { name: '客服', max: 10000 },
        { name: '研发', max: 10000 },
        { name: '市场', max: 10000 }
      ]
    },
    series: [{
      name: '预算 vs 开销',
      type: 'radar',
      data: [
        {
          value: [5000, 7000, 6000, 4000, 8000, 3000],
          name: '预算分配'
        },
        {
          value: [4000, 6000, 5500, 3500, 7500, 2500],
          name: '实际开销'
        }
      ]
    }]
  }

  try {
    // 使用 trySetOption 方法
    chart.value.setOption(option, true)
  } catch (error) {
    console.error('设置图表选项时出错:', error)
  }
}

watch(() => props.chartData, (newValue) => {
  if (chart.value && newValue) {
    try {
      chart.value.setOption({
        series: [{
          data: newValue
        }]
      })
    } catch (error) {
      console.error('更新图表数据时出错:', error)
    }
  }
}, { deep: true })

onMounted(() => {
  initChart()
  window.addEventListener('resize', handleResize)
})

// 添加重绘方法
const resize = () => {
  if (chart.value) {
    chart.value.resize()
  }
}

// 暴露方法给父组件
defineExpose({
  resize
})

onBeforeUnmount(() => {
  if (chart.value) {
    chart.value.dispose()
    chart.value = null
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style lang="scss" scoped>
.radar-chart {
  width: 100%;
  height: 100%;
}
</style>
